﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>课程预报名</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <link rel="stylesheet" href="http://g.alicdn.com/msui/sm/0.6.2/css/sm.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/app.css">

</head>
<body>
    <div class="page">
        <header class="bar bar-nav">
            <a href="my_profile.html" class="icon icon-me pull-right"></a>
            <h1 class="title">微报名</h1>
        </header>
        <div class="content">
            <!-- 这里是页面内容区 -->

        </div>
    </div>

    <!-- 选择课程 -->
    <script type="text/html" id="tmplCoursesList">
        <div class="buttons-tab">
            <a href="#tab1" class="tab-link active button">课程</a>
            <a href="#tab2" class="tab-link button">活动</a>
        </div>

        <div class="tabs" style="margin-bottom: 3rem;">
            <div id="tab1" class="tab active">
                {{each courses item index}}
                <div class="card" data_name="{{item.title}}">
                    <div class="card-content">
                        <div class="card-content-inner" data_id="{{item.id}}">{{item.title}}<span style="display: none;">{{if hasProperty(jsonParse(item.settingsXml), "teacher")}}{{jsonParse(item.settingsXml).teacher}}{{/if}}</span></div>
                    </div>
                </div>
                {{/each}}
            </div>
            <div id="tab2" class="tab">
                {{each activities item index}}
                <div class="card" data_name="{{item.title}}">
                    <div class="card-content">
                        <div class="card-content-inner" data_id="{{item.id}}">{{item.title}}</div>
                    </div>
                </div>
                {{/each}}
            </div>
        </div>

        <nav class="bar bar-tab" style="position: fixed;bottom: 0;padding-right: 0;padding-left: 0;height: auto;">
            <span class="big-nav" id="btnEnroll">报名</span>
        </nav>
    </script>

    <!--课程报名反馈-->
    <script type="text/html" id="tmplFeedback">
        <h1 class="text-center">{{title}}</h1>
        <div class="text-center">
            {{if category == 'success'}}
            <p>您有 <span style="font-weight: bold;">{{count}}</span> 门课程报名成功 !</p>
            {{else}}
            <p>对不起，每人限报 <span style="font-weight: bold;">{{limitCount}}</span> 门课程</p>
            <p>您当前最多只能报 <span style="font-weight: bold;">{{count}}</span> 门课程</p>
            {{/if}}
        </div>
        <div class="content-block">
            <p><span class="button button-big button-round button-primary" id="btnOk">确定 </span></p>
        </div>
    </script>

    <script type='text/javascript' src='assets/js/zepto.min.js' charset='utf-8'></script>
    <script>
        $.config = { router: false };
    </script>
    <script type='text/javascript' src='assets/js/sm.min.js' charset='utf-8'></script>
    <!--<script type='text/javascript' src='http://g.alicdn.com/msui/sm/0.6.2/js/sm-extend.min.js' charset='utf-8'></script>-->
    <script type="text/javascript" src="assets/js/template-web.js"></script>
    <script type="text/javascript" src="assets/js/director.min.js"></script>
    <script type="text/javascript" src="assets/js/axios-0.17.1.min.js"></script>
    <script type="text/javascript" src="assets/js/utils.js"></script>

    <script type="text/javascript">
        template.defaults.imports.jsonParse = function (strJson) {
            var result = {};
            result = JSON.parse(strJson);
            return result;
        }

        template.defaults.imports.hasProperty = function (json, strPropertyName) {
            return json.hasOwnProperty(strPropertyName);
        }

        var instance = axios.create({

            //headers: { 'X-SS-API-KEY': 'ced47c42-5377-4d7b-b805-0e9af6afd0c9' }
            headers: { 'X-SS-API-KEY': 'b080cfcd-ee50-4bc9-8651-6241b428d3a0' }
        });

        var user = {};
        var rules = {};
        var myCourses = {};
        var limitEnrollmentsCount = 2;
        var data = {};
        data.courses = [];
        data.activities = [];

        $.init();

        var page = {
            IsValidAge: function (expr) {
                if (expr.relation === "<=") {
                    if (user.value.age <= expr.value) {
                        return 0;
                    } else {
                        return 1
                    }
                }

                if (expr.relation === ">=") {
                    if (user.value.age >= expr.value) {
                        return 0;
                    } else {
                        return 1
                    }
                }

                if (expr.relation === "=") {
                    if (user.value.age === expr.value) {
                        return 0;
                    } else {
                        return 1
                    }
                }
            },
            IsValidGender: function (expr) {

                if (expr.value === user.value.gender) {
                    return 0;
                } else {
                    return 1;
                }
            },
            IsValidCourse: function (course) {
                //如果当前用户有一项条件与要求不符则result加1
                var result = 0;
                if (course.groupNameCollection === null || course.groupNameCollection === "") {
                    result = 0;
                } else {
                    var courseRules = course.groupNameCollection.split(",");
                    console.log(courseRules);

                    var expr = {};
                    $.each(courseRules, function (index, item) {
                        console.log(item);

                        $.each(rules.value, function (i, r) {
                            if (r.groupName === item) {
                                //ruleExprs.push(JSON.parse(r.description));
                                console.log(JSON.parse(r.description));
                                expr = JSON.parse(r.description);
                                console.log(expr.attr);

                                if (expr.attr === "age") { result = result + page.IsValidAge(expr); }
                                if (expr.attr === "gender") { result = result + page.IsValidGender(expr); }
                            }
                        })

                    });
                }

                return result;
            },
            GetUserInfo: function () {

                if (getCookie("lndx_user") === "") {
                    //获取用户信息
                    window.location.href = "index.html";
                } else {
                    user.value = JSON.parse(getCookie("lndx_user"));
                    user.value.age = IdCard(user.value.citizenCode, 3);
                    user.value.gender = IdCard(user.value.citizenCode, 2);
                }


            },
            GetRules: function () {
                //获取全部限制条件
                instance.get('/api/v1/stl/sqlContents?queryString=SELECT * FROM siteserver_ContentGroup where siteId=1')
                    .then(function (response) {
                        console.log(response.data);
                        rules.value = response.data.value;
                    });
            },
            GetMyCourses: function () {
                //获取我的课程
                instance.get('/api/ss.lndx.service/enrollment/' + user.value.id + '/2')
                    .then(function (response) {
                        console.log(response.data);
                        myCourses.value = response.data.value;
                        console.log(myCourses.value.length);
                    });
            },
            GetValidContents: function (parentId) {
                return instance.get('/api/ss.lndx.service/content/valid?parentId=' + parentId + "&userId=" + user.value.id);
            },
            GetActivitiesList: function () {
                return page.GetValidContents(1);
            },
            GetCoursesList: function () {
                return page.GetValidContents(2);
            },
            RenderContentsList: function () {
                var actions = [];
                actions.push(page.GetCoursesList());
                actions.push(page.GetActivitiesList());
                axios.all(actions).then(axios.spread(function (coursesResp, activitiesResp) {
                    console.log(coursesResp.data);
                    console.log(activitiesResp.data);
                    data.courses = [];
                    data.activities = [];

                    $.each(coursesResp.data, function (index, item) {

                        //console.log(item.limitCount);
                        if (page.IsValidCourse(item) === 0) {
                            data.courses.push(item);
                        }
                    });
                    $.each(activitiesResp.data, function (index, item) {

                        console.log(item.limitCount);
                        if (page.IsValidCourse(item) === 0) {
                            data.activities.push(item);
                        }
                    });

                    //绑定数据到页面
                    var html = template("tmplCoursesList", data);
                    $(".content").html(html);
                }));
            },
            RenderFeedback: function (data) {
                var html = template("tmplFeedback", data);
                $(".content").html(html);
            },
            AddEnrollment: function (contentId, userId) {
                instance.post('/api/ss.lndx.service/enrollment', { 'contentId': contentId, 'userId': userId })
                    .then(function (response) {
                        console.log("enroll success");
                    });
            },
            AddEnrollments: function (contentIds) {
                var feedback = {};
                //判断是否超过报名课程数量限制
                if (contentIds.length + myCourses.value.length > limitEnrollmentsCount) {

                    feedback.category = "failure";
                    feedback.title = "报名失败";
                    feedback.limitCount = limitEnrollmentsCount;
                    feedback.count = limitEnrollmentsCount - myCourses.value.length > 0 ? limitEnrollmentsCount - myCourses.value.length : 0;
                    page.RenderFeedback(feedback);
                } else {

                    var actions = [];
                    $.each(contentIds, function (index, item) {
                        actions.push(page.AddEnrollment(item, user.value.id));
                    });
                    axios.all(actions).then(axios.spread(function (acct, perms) {
                        
                        feedback.category = "success";
                        feedback.title = "报名成功";
                        feedback.count = contentIds.length;
                        page.RenderFeedback(feedback);
                    }));
                }
                
            },
            BindEvents: function () {
                $(".content").on("click", "#btnEnroll", events.Enroll.bind(this));
                $(".content").on("click", ".card", events.CheckCourse.bind(this));
                $(".content").on("click", "#btnOk", events.Ok.bind(this));
            }
        };

        var events = {
            Enroll: function (e) {
                var contentIds = [];
                $(".card .active").each(function () {
                    var id = $(this).attr("data_id");
                    console.log(id);
                    contentIds.push(id);
                });
                page.AddEnrollments(contentIds);
            },
            CheckCourse: function (e) {
                if ($(e.target).find("span.icon").length == 0) {
                    $(e.target).append("<span class='icon icon-check pull-right'></span>").addClass("active");
                } else {
                    $(e.target).removeClass("active").find("span").remove();
                }
            },
            Ok: function (e) {
                page.RenderContentsList();
                console.log("feedback");
            }
        }

        page.GetUserInfo();
        page.GetRules();
        page.GetMyCourses();

        $(document).ready(function () {
            var routes = {
                "/": function () { page.RenderContentsList(); }
            };

            var router = Router(routes);
            router.configure({
                on: function () { page.BindEvents(); }
            })

            router.init("/");
        });


    </script>
</body>
</html>